﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Yyyg.IBLL;
using Yyyg.Models;
using Yyyg.WebUI.Models;

namespace Yyyg.WebUI.Controllers
{
    [Authorize]
    public class PayController : Controller
    {
        static string verifyTokenName = "OrderToken";

        IOrdersService ordersService;

        public PayController(IOrdersService ordersService)
        {
            this.ordersService = ordersService;
        }

        [HttpGet]
        public ActionResult PayIndex(string bys, bool sig = false)
        {
            //购物车不存在则返回主页
            if (string.IsNullOrEmpty(bys)) return Redirect("/home/index");
            var bylist = JsonConvert.DeserializeAnonymousType(bys, new[] { new { rushID = 0, byCount = 0 } });
            //没有商品则返回主页
            if (bylist.Length == 0) return Redirect("/home/index");
            //拼接sql 避免多次查询
            StringBuilder str = new StringBuilder();
            for (int i = 0; i < bylist.Length; i++) str.Append(i == bylist.Length - 1 ? bylist[i].rushID.ToString() : bylist[i].rushID + ",");
            string sql = "select * from dbo.Rushby_all where Id in(" + str + ")";
            using (LuckyEntities db = new LuckyEntities())
            {
                var res = db.Rushby_all.SqlQuery(sql);
                var s = res.ToList();
                var reslist = s.Select(sl => new ByItem()
                {
                    ByCount = bylist.First(f => f.rushID == sl.Id).byCount,
                    Good = sl.Goods,
                    RushInfo = sl,
                }).ToList();
                var uid = HttpContext.GetUserID();
                ViewBag.Rece = db.ReceInfo.Where(r => r.Uid == uid).ToArray();
                //附带token标记，防止用户重复提交订单
                this.HttpContext.SetTokenByGuid(verifyTokenName);
                Session.Add("issig", sig);
                return View(reslist);
            }
        }

        [HttpPost]
        public JsonResult Pay(string byinfo = "")
        {
            PostResult result = new PostResult();

            var info = JsonConvert.DeserializeAnonymousType(byinfo, new
            {
                seladdr = 0,
                bys = new List<OrderItem>(),
            });

            if (!this.HttpContext.CheckGuidToken(verifyTokenName))
            {
                result.ErrorMsg = "Token verification failed";
                result.Isucc = false;
                return Json(result);
            }

            if (info.bys.Count == 0)
            {
                result.ErrorMsg = "Bys is null";
                result.Isucc = false;
                return Json(result);
            }

            try
            {
                int uid = HttpContext.GetUserID();
                ordersService.CommitOrder(info.bys, uid, info.seladdr);
                //如果是购物车提交则清空购物车
                if (!(bool)Session["issig"])
                {
                    HttpCookie hc = Request.Cookies["shopCar"];
                    hc.Expires = DateTime.Now.AddDays(-1);
                    Response.AppendCookie(hc);
                }
                this.HttpContext.DelGuidToken(verifyTokenName);
                result.Isucc = true;
            }
            catch (Exception ex)
            {
                result.ErrorMsg = ex.Message;
                result.Isucc = false;
            }
            return Json(result);
        }

        public ActionResult TuPage()
        {
            return View("_PartiaTopUp");
        }

        [HttpPost]
        public JsonResult TopUp(int pric)
        {
            PostResult result = new PostResult();
            int uid = HttpContext.GetUserID();
            using (LuckyEntities db = new LuckyEntities())
            {
                var user = db.Member.FirstOrDefault(f => f.Uid == uid);
                user.Acbal += pric;
                db.SaveChanges();
                result.Isucc = true;
            }
            return Json(result);
        }
    }

}